import koa from 'koa'
import Router from 'koa-router'
import cors from'@koa/cors'
import bodyParser from 'koa-bodyparser'
import { DataTypes, Op, Sequelize } from 'sequelize'

const app=new koa()
const router=new Router()

app.use(cors())
app.use(bodyParser())

let sequelize =new Sequelize('book','root','123456',{
    dialect:'mysql',
    host:'localhost'
})

let book=sequelize.define('book',{
    bookName:{
        type:DataTypes.STRING,
        allowNull:false
    },
    author:{
        type:DataTypes.STRING,
        allowNull:false
    }
})

await sequelize.sync()

await book.bulkCreate([
   {
    bookName:'龙族',
    author:'江南'
   },
   {
    bookName:'夜的命名术',
    author:'会说话的肘子'
   }
])

router.get('/book',async (ctx) => {
    let keyword=ctx.request.query.keyword || ''
    console.log(keyword);
    
    let result;
    if (keyword) {
        result=await book.findAll({
            where:{
                [Op.or]:{
                    bookName:{
                        [Op.like]:`%${keyword}%`
                    },author:{
                        [Op.like]:`%${keyword}%`
                    },
                }
            }
        })
    } else {
        result=await book.findAll()
    }
    ctx.body={
        code:1000,
        data:result,
        msg:'查询成功'
    }
})

router.get('/book/:id',async (ctx) => {
    let id=ctx.params.id || 0;
    let book=await book.findByPk(id)
    ctx.body={
        code:1000,
        data:book,
        msg:'查询成功'
    }
})

router.post('/book',async (ctx) => {
    let obj=ctx.request.body;
    let result=await book.create(obj);
    ctx.body={
        code:1000,
        data:result,
        msg:'新增成功'
    }
})

router.put('/book/:id',async (ctx)=>{
    let id=ctx.params.id || 0;
    let obj=ctx.request.body;
    let result=await book.update(ojb,{where:{id}});
    ctx.body={
        code:1000,
        data:result,
        msg:'修改成功'
    }
})

router.delete('/book/:id',async (ctx) => {
    let id=ctx.params.id || 0;
    let result= await book.destroy({where:{id}})
    ctx.body={
        code:1000,
        data:result,
        msg:'删除成功'
    }
})
app.use(router.routes())
let port=3000
app.listen(port)

console.log(`server running on http://localhost:${port}`);
